#include "hc05.h"

#include "usart.h"
#include "ws2812.h"

Hc_HandleTypeDef hhc;

void Hc_Init(void) {
  hhc.bufin[0] = 0;
  hhc.bufout[0] = 0;
  hhc.mode = 0;
  hhc.idx = 0;
  HAL_UART_Init(&huart1);
  HAL_UART_Receive_IT(&huart1, hhc.bufin, 1);
}

void Hc_Put(uint8_t *data) {
  if (hhc.mode) {
    // 当前处于接收模式，先改成发送模式
    hhc.bufout[0] = 0;
    hhc.bufin[0] = 0;
    HAL_UART_Transmit(&huart1, hhc.bufout, 1, 0xFFFF);
    while (hhc.bufin[0] == 0);
  }
  hhc.bufin[0] = 0;
  HAL_UART_Transmit(&huart1, (uint8_t *)data, 1, 0xFFFF);
  while (hhc.bufin[0] == 0);
}

void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart) {
  if (huart->Instance == USART1) {
    HAL_UART_Receive_IT(&huart1, hhc.bufin, 1);
    if (hhc.mode) {
      // 处于图片数据接收模式
      hhc.matrix[hhc.idx] = hhc.bufin[0];
      hhc.idx++;
      if (hhc.idx >= 1023) {
        hhc.mode = 0;
        hhc.idx = 0;
      }
      return;
    } else
      // 处于命令接收模式
      switch (hhc.bufin[0]) {
        case 'M':
          hhc.M = 1;
          break;
        case 'U':
          hhc.U = 1;
          break;
        case 'D':
          hhc.D = 1;
          break;
        case 'L':
          hhc.L = 1;
          break;
        case 'R':
          hhc.R = 1;
          break;
        case 'm':
          hhc.M = 0;
          break;
        case 'u':
          hhc.U = 0;
          break;
        case 'd':
          hhc.D = 0;
          break;
        case 'l':
          hhc.L = 0;
          break;
        case 'r':
          hhc.R = 0;
          break;
      }
  }
}
